import React from 'react'
import './draw.less'

/**
 * @desc 学生抽签组件 TODO: 学生数据为空
 */
class Draw extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentName: '' // 当前学生名字
    }
    this.students = this.shuffle(props.students)
    this.timer = null
  }

  /**
   * @desc 加载计时器
   */
  componentDidMount() {
    this.timer = setInterval(() => {
      this.tick()
    }, 100)
  }

  /**
   * @desc 清除计时器
   */
  componentWillUnmount() {
    this.timer && clearInterval(this.timer)
    this.timer = null
  }

  /**
   * @desc 打乱数组
   * @param 数组
   */
  shuffle(items) {
    items = items.slice()
    let i, j, k
    let l = items.length
    for (i = l - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1))
      k = items[i]
      items[i] = items[j]
      items[j] = k
    }
    return items
  }

  /**
   * @desc 随机学生名字
   */
  tick() {
    let l = this.students.length
    let i = Math.floor(Math.random() * l)

    this.setState({
      currentName: this.students[i]
    })
  }

  render() {
    return <div id="draw">{this.state.currentName}</div>
  }
}

export default Draw
